package com.cjm.algorithm.str;

public class Ti240422541 {
    public static void main(String[] args) {
        Ti240422541 solution = new Ti240422541();
        System.err.println(solution.reverseStr("abcdefg", 2));
    }

    public String reverseStr(String s, int k) {
        char[] cs = s.toCharArray();
        int n = s.length();
        for (int l = 0; l < n; l = l + 2 * k) {
            int r = l + k - 1;
            reverse(cs, l, Math.min(r, n - 1));
        }
        return String.valueOf(cs);
    }

    void reverse(char[] cs, int l, int r) {
        while (l < r) {
            char c = cs[l];
            cs[l] = cs[r];
            cs[r] = c;
            l++;
            r--;
        }
    }


    public String reverseStr1(String s, int k) {
        int len = s.length();
        int i = len / (2 * k) - 1;
        int j = (len % (2 * k)) % k;
        StringBuffer sb = new StringBuffer();
        int x = 0;
        while (x <= i) {
            int start = x * k * 2;
            int end = start + 2 * k - 1;

            char[] charArray = s.substring(start, end).toCharArray();
            for (int m = 0; m < charArray.length / 2; m++) {
                char a = charArray[m];
                charArray[m] = charArray[charArray.length - 1 - m];
                charArray[charArray.length - 1 - i] = a;
            }
            for (char c : charArray) {
                sb.append(c);
            }
            x++;
        }

        if (j >= k) {
            int start = (i + 1) * k * 2;
            int end = start + k - 1;
            char[] charArray = s.substring(start, end).toCharArray();
            for (int m = 0; m < charArray.length / 2; m++) {
                char a = charArray[m];
                charArray[m] = charArray[charArray.length - 1 - m];
                charArray[charArray.length - 1 - i] = a;
            }
            for (char c : charArray) {
                sb.append(c);
            }
        } else {
            int start = (i + 1) * k * 2;
            char[] charArray = s.substring(start).toCharArray();
            for (int m = 0; m < charArray.length / 2; m++) {
                char a = charArray[m];
                charArray[m] = charArray[charArray.length - 1 - m];
                charArray[charArray.length - 1 - i] = a;
            }
            for (char c : charArray) {
                sb.append(c);
            }
        }

        String string = sb.toString();
        return string;
    }
}
